import DatabaseUtils from "../utils/db-utils";
import {BOOLEAN, ROOM_STATUS} from "../configs/config";

class ValidCodeDao {

    /**
     * 创建验证码信息
     * @param userId
     * @param email
     * @param validCode
     * @param codeType
     * @returns {Promise<boolean>}
     */
    static createValidCode = async (userId: string, email: string, validCode: string, codeType: string) => {
        const sql = `insert into t_code(user_id, email, valid_code, data_status, code_type) values (?, ?, ?, ?, ?)`;
        const params = [userId, email, validCode, BOOLEAN.SHORT_YES, codeType];
        const rows: any = await DatabaseUtils.execSql(sql, params);
        return rows.length === 1;
    }

    /**
     * 更新验证码的状态
     * @param userId
     * @param email
     * @param validCode
     * @param dataStatus
     * @returns {Promise<boolean>}
     */
    static updateValidCodeStatus = async (userId: string, email: string, validCode: string, dataStatus: string) => {
        const sql = `update t_code set data_status = ? where user_id = ? and email = ? and valid_code = ?`;
        const params = [dataStatus, userId, email, validCode];
        const rows: any = await DatabaseUtils.execSql(sql, params);
        return rows.length === 1;
    }


    /**
     * 校验验证码是否合法
     * @param userId
     * @param email
     * @param validCode
     * @param validTimeMinutes
     * @returns {Promise<boolean>}
     */
    static validateEmailAndCode = async (userId: string, email: string, validCode: string, validTimeMinutes: number) => {
        const sql = `select valid_code as validCode, data_status as dataStatus from t_code where user_id = ? and email = ? 
              and timestampdiff(minute, create_time, now()) <= ? order by create_time desc limit 1`;
        const params = [userId, email, validTimeMinutes];
        const rows: any = await DatabaseUtils.execSql(sql, params);
        if (rows.length === 0) {
            return false;
        } else {
            const [data] = rows;
            return data.validCode === validCode && data.dataStatus === BOOLEAN.SHORT_YES;
        }
    }

    /**
     * 获取当天已经发送过的邮件次数
     * @param userId
     * @param to
     * @returns {Promise<null|*>}
     */
    static getTodaySendEmailCount = async (userId: string, to: string) => {
        const sql = `select count(*) as total from t_code where user_id = ? and email = ? 
            and date_format(create_time, '%Y-%m-%d') = date_format(now(), '%Y-%m-%d')`;
        const params = [userId, to];
        const rows: any = await DatabaseUtils.execSql(sql, params);
        return rows.length === 0 ? null : rows[0].total;
    }

}

export default ValidCodeDao;